from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.naive_bayes import MultinomialNB

def nb_cls():
    """
    朴素贝叶斯对新闻数据集进行预测
    :return:
    """
    # 1.获取新闻的数据
    news = fetch_20newsgroups(subset='all')
    # 2.进行数据集分割
    x_train, x_test, y_train, y_test = train_test_split(news.data, news.target,test_size=0.3)
    # 3.对于文本数据，进行特征抽取
    transfer = TfidfVectorizer()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)

    # 4.estimator估计器流程，朴素贝叶斯算法
    mlb = MultinomialNB(alpha=1.0)
    mlb.fit(x_train, y_train)
    # 5.进行预测
    y_predict = mlb.predict(x_test)
    print("预测每篇文章的类别：", y_predict[:100])
    print("真实类别为：", y_test[:100])
    print("预测准确率为：", mlb.score(x_test, y_test))
    return None

if __name__ == "__main__":
    # 代码13：朴素贝叶斯对新闻数据集进行预测
    nb_cls()